package com.luyinbros.imagepicker;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.luyinbros.imagepicker.model.LocalMedia;
import com.luyinbros.imagepicker.model.LocalMediaFolder;
import com.luyinbros.imagepicker.util.LocalMediaLoader;
import com.luyinbros.imagepicker.util.MediaFileManager;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Description:图片选择器
 * * 图片选择
 * Intent intent==new Intent({你的context} , ImagePickerActivity.this);
 * intent.put({"maxNum",{>0})    最大选择数量 默认为1
 * intent.put("showCamera",{true | false})    是否开启拍照item，如果最大选择数量大于1，则设置此项无效果 (可选)
 * intent.put("enablePreview",{true | false})  是否开启浏览 （可选）
 * intent.put("enableCrop",{true | false})  是否剪裁 如果最大选择数量大于1 则设置此项无效果（可选）
 * startActivityForResult(intent,{你的requestCode});
 * 接收
 * * if (resultCode == 4501) {
 * List<LocalMedia> list = (List<LocalMedia>) intent.getSerializableExtra("imagePathList);//返回数据不可能为null
 * }
 * Created by Andy Hong on 6/18/2017.
 */

public class ImagePickerActivity extends AppCompatActivity {
    private static final String TAG = "ImagePickerActivity";
    private TextView tvDone;
    private TextView tvFolderName;
    private TextView actionPreview;
    private ViewGroup bottomNavigate;
    private FolderWindow folderWindow;
    private RecyclerView mRecyclerView;
    private ImagePickerAdapter mAdapter;
    private int maxSelectNum;
    private boolean showCamera = false;
    private boolean enablePreview = false;
    private boolean enableCrop = false;

    public String cameraPath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        maxSelectNum = intent.getIntExtra("maxNum", 1);
        if (maxSelectNum != 1) {
            enablePreview = intent.getBooleanExtra("enablePreview", false);
        }
        if (maxSelectNum == 1) {
            showCamera = intent.getBooleanExtra("showCamera", false);
            enableCrop = intent.getBooleanExtra("enableCrop", false);
        }

        if (savedInstanceState != null) {
            cameraPath = savedInstanceState.getString("cameraPath");
        }

        setContentView(R.layout.activity_image_picker);

        tvDone = (TextView) findViewById(R.id.action_done);
        tvFolderName = (TextView) findViewById(R.id.tv_folder_name);
        actionPreview = (TextView) findViewById(R.id.action_preview);
        mRecyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);
        bottomNavigate = (ViewGroup) findViewById(R.id.navigate_bottom);

        folderWindow = new FolderWindow(this);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mAdapter = new ImagePickerAdapter(this, showCamera, maxSelectNum);
        mRecyclerView.setAdapter(mAdapter);

        if (maxSelectNum == 1) {
            actionPreview.setVisibility(View.GONE);
            tvDone.setVisibility(View.GONE);
        } else {
            actionPreview.setEnabled(false);
            tvDone.setEnabled(false);
        }


        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        setOnDoneClickListener();
        setOnFolderClickListener();
        setOnPreviewClickListener();
        setOnFolderItemClickListener();
        mAdapter.setOnImageSelectedClickListener(new ImagePickerAdapter.OnImageSelectedListener() {

            @SuppressWarnings("all")
            @Override
            public void takePhoto() {
                ActivityCompat.requestPermissions(ImagePickerActivity.this, new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }

            @Override
            public void onPictureClick(int position) {

                if (maxSelectNum > 1) {
                    Intent previewIntent = new Intent(ImagePickerActivity.this, ImagePreviewActivity.class);
                    previewIntent.putExtra("startPosition", position);
                    previewIntent.putExtra("maxSelectNum", maxSelectNum);
                    previewIntent.putExtra("select", (ArrayList<LocalMedia>) mAdapter.getSelectList());
                    previewIntent.putExtra("folderName", folderWindow.getSelectedFolder().getName());
                    //previewIntent.putExtra("all", (ArrayList<LocalMedia>) mAdapter.getAllList());
                    startActivityForResult(previewIntent, 2);
                } else if (enableCrop) {
                    Intent intent = new Intent(ImagePickerActivity.this, ImageCropActivity.class);
                    intent.putExtra("path", mAdapter.getItem(position).getPath());
                    startActivityForResult(intent, 3);
                } else {
                    ArrayList<LocalMedia> list = new ArrayList<>();
                    list.add(mAdapter.getItem(position));
                    setResult(list);
                    finish();
                }

            }

            @Override
            public void onSelected(List<LocalMedia> localMediaList) {
                if (localMediaList.size() == 0) {
                    actionPreview.setText(R.string.preview);
                    actionPreview.setEnabled(false);
                    tvDone.setText(R.string.complete);
                    tvDone.setEnabled(false);
                } else {
                    actionPreview.setEnabled(true);
                    actionPreview.setText(String.format(getString(R.string.format_preview), localMediaList.size()));
                    tvDone.setEnabled(true);
                    tvDone.setText(String.format(getString(R.string.format_image_num), localMediaList.size(), maxSelectNum));
                }

            }
        });

        new LocalMediaLoader(this, LocalMediaLoader.TYPE_IMAGE).loadAllImages(new LocalMediaLoader.LocalMediaLoadListener() {
            @Override
            public void loadComplete(List<LocalMediaFolder> folders) {
                if (folders != null && folders.size() != 0) {
                    folderWindow.bindFolder(folders);
                    mAdapter.updateList(folders.get(0).getImages());
                }

            }
        });
    }

    /**
     * 完成
     */
    private void setOnDoneClickListener() {
        tvDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(mAdapter.getSelectList());
                finish();
            }
        });
    }

    /**
     * 打开图片文件夹
     */
    private void setOnFolderClickListener() {
        findViewById(R.id.container_folder).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (folderWindow.isShowing()) {
                    folderWindow.dismiss();
                } else {
                    folderWindow.show(bottomNavigate);
                }
            }
        });
    }

    /**
     * 浏览
     */
    private void setOnPreviewClickListener() {
        actionPreview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (maxSelectNum != 1) {
                    Intent previewIntent = new Intent(ImagePickerActivity.this, ImagePreviewActivity.class);
                    previewIntent.putExtra("startPosition", 0);
                    previewIntent.putExtra("maxSelectNum", maxSelectNum);
                    previewIntent.putExtra("select", (ArrayList<LocalMedia>) mAdapter.getSelectList());
                    previewIntent.putExtra("all", (ArrayList<LocalMedia>) mAdapter.getSelectList());
                    startActivityForResult(previewIntent, 2);
                }
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("cameraPath", cameraPath);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {     //拍照
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(cameraPath))));
            if (enableCrop) {
                Intent intent = new Intent(ImagePickerActivity.this, ImageCropActivity.class);
                intent.putExtra("path", cameraPath);
                startActivityForResult(intent, 3);
            } else {
                ArrayList<LocalMedia> list = new ArrayList<>();
                list.add(new LocalMedia(cameraPath));
                setResult(list);
                finish();
            }
        } else if (requestCode == 2) {   //浏览
            mAdapter.updateSelectList((List<LocalMedia>) data.getSerializableExtra("select"));
            int selectSize = mAdapter.getSelectList().size();
            if (selectSize == 0) {
                actionPreview.setText(R.string.preview);
                actionPreview.setEnabled(false);
                tvDone.setText(R.string.complete);
                tvDone.setEnabled(false);
            } else {
                actionPreview.setEnabled(true);
                actionPreview.setText(String.format(getString(R.string.format_preview), selectSize));
                tvDone.setEnabled(true);
                tvDone.setText(String.format(getString(R.string.format_image_num), selectSize, maxSelectNum));
            }
        } else if (requestCode == 3) {     //裁剪
            if (resultCode == 1742) {
                ArrayList<LocalMedia> list = new ArrayList<>();
                list.add(new LocalMedia(data.getStringExtra("outPath")));
                setResult(list);
                finish();
            }

        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }

    }

    private void setResult(List<LocalMedia> list) {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("imagePathList", (Serializable) list);
        setResult(1741, resultIntent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //拍照
        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                    || grantResults[1] == PackageManager.PERMISSION_GRANTED
                    || grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (cameraIntent.resolveActivity(getPackageManager()) != null) {
                    File cameraFile = MediaFileManager.createImageFile(ImagePickerActivity.this);
                    cameraPath = cameraFile.getAbsolutePath();
                    Uri uri = MediaFileManager.createMediaUri(ImagePickerActivity.this, cameraFile);
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    startActivityForResult(cameraIntent, 1);
                }
            } else {
                Toast.makeText(this, R.string.take_picture_permission_denied, Toast.LENGTH_SHORT).show();
            }

        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

    private void setOnFolderItemClickListener() {
        folderWindow.setOnItemClickListener(new FolderWindow.OnItemClickListener() {
            @Override
            public void onItemClick(String folderName, List<LocalMedia> images) {
                folderWindow.dismiss();
                mAdapter.updateList(images);
                tvFolderName.setText(folderName);
                mRecyclerView.smoothScrollToPosition(0);
            }
        });
    }

}
